package m202401.d07;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/7 10:02
 */
//61. 旋转链表
public class Q61 {
    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        new Q61().rotateRight(n1, 2);
    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0) {
            return head;
        }
        int count = 0;
        ListNode p = head;
        ListNode last = null;
        while (p != null) {
            if (p.next == null) {
                last = p;
            }
            p = p.next;
            count++;
        }
        k = k % count;
        if (k == 0) {
            return head;
        }
        k = count - k;
        p = head;
        int i = 0;
        while (i < k - 1) {
            p = p.next;
            i++;
        }
        ListNode res = p.next;
        p.next = null;
        last.next = head;
        return res;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
